import time

import numpy as np
from selenium.webdriver.common.action_chains import ActionChains


def ease_out_quad(x):
    return 1 - (1 - x) * (1 - x)


def ease_out_quart(x):
    return 1 - pow(1 - x, 4)


def ease_out_expo(x):
    if x == 1:
        return 1
    else:
        return 1 - pow(2, -10 * x)


def get_tracks(distance, seconds):
    """
    :param distance: offset
    :param seconds: 拉动时间
    :return:
    """
    tracks = [0]
    offsets = [0]
    # print("np_value:", np.arange(0.0, seconds, 0.1))
    for t in np.arange(0.0, seconds, 0.1):
        offset = round(ease_out_quart(t / seconds) * distance)
        tracks.append(offset - offsets[-1])
        offsets.append(offset)
    return offsets, tracks


def drag_and_drop(browser, offset, knob):
    """
    拖拽
    :param browser: 浏览器对象
    :param offset: 滑块到缺口的距离
    :param knob: 滑块的位置
    """
    offsets, tracks = get_tracks(offset, 12)
    # print("offsets:", offsets)
    # print("tracks:", tracks)
    ActionChains(browser).click_and_hold(knob).perform()
    for x in tracks:
        ActionChains(browser).move_by_offset(x, 0).perform()
    ActionChains(browser).pause(0.5).release().perform()


def do_captcha(offset,driver,ele):
    """
        实现处理验证码
    """
    # 根据滑块本身的大小以及承载滑块的div的大小来获取偏移量offx
    # slide1_back = self.find_ele_is_presence(_slide1_back_locate)
    # slide1_span = self.find_ele_is_presence(_slide1_span_locate)
    # 获取滑块的起始坐标location
    # start_location = slide1_span.location
    # # 获取滑块所在长条的长宽大小
    # background_size = slide1_back.size
    # 4.滑块的滑动范围[开始位置的横坐标加上滑片的宽度],由于是平移所以纵坐标没有变化
    # x_location = background_size["width"] - start_location["x"]
    # y_location = start_location["y"]

    offset = offset - 10
    print("offset:", offset)

    # todo 这使用加速度拖动，被极限识别，无法通过验证
    # 使用偏移值计算移动操作
    # track = self.get_track(offset)
    # 操作滑块按钮，模拟拖动滑块做验证登录
    # self.operate_slider(track)

    # todo 使用jquery自定义的移动轨迹拖动，通过验证
    # slider_bt = driver.find_element_by_xpath("//div[@class='geetest_slider_button']")
    drag_and_drop(driver, offset + 40, ele)
    time.sleep(8)
